using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;
using GraphAlgsPresentation.Core;
using System.Diagnostics;

namespace GraphAlgsPresentation.ScriptLibrary
{
    /// <summary>
    /// Represents the script of presentation
    /// </summary>
    public class Script
    {
        private Context context = new Context();

        /// <summary>
        /// Gets or sets the context.
        /// </summary>
        /// <value>The context.</value>
        public Context Context
        {
            get { return context; }
            set { context = value; }
        }

        private List<List<Command>> commands = new List<List<Command>>();

        /// <summary>
        /// returns list of commands
        /// </summary>
        public List<List<Command>> Commands
        {
            get { return commands; }
            set { commands = value; }
        }

        private static XmlSerializer serializer;

        /// <summary>
        /// Initializes the <see cref="Script"/> class.
        /// </summary>
        static Script()
        {
            List<Type> commandTypes = new List<Type>();
            foreach (Type t in typeof(Command).Assembly.GetTypes())
            {
                if (t.BaseType == typeof(Command))
                {
                    commandTypes.Add(t);
                }
            }
            serializer = new XmlSerializer(typeof(Script), commandTypes.ToArray());
        }

        /// <summary>
        /// Serializes the script to XML.
        /// </summary>
        /// <param name="output">The output.</param>
        public void Serialize(TextWriter output)
        {
            serializer.Serialize(output, this);
        }

        /// <summary>
        /// Deserializes the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static Script Deserialize(TextReader input)
        {
            Script result = serializer.Deserialize(input) as Script;
            result.Context.LayoutContext.Refresh();
            foreach (List<Command> lstCmd in result.Commands)
                foreach (Command cmd in lstCmd)
                    cmd.Context = result.Context;
            return result;
        }
    }
}
